package org.springsocial.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springsocial.dao.PlayerDao;
import org.springsocial.domain.Player;
import org.springsocial.nullobjects.NullPlayer;
import org.springsource.util.ActiveTweeter;

@Repository
public class PlayerDaoImpl extends AbstractJpaDao<Player> implements PlayerDao {
	private static final Logger logger = LoggerFactory.getLogger(PlayerDaoImpl.class);
	
	public PlayerDaoImpl(){
	      setClazz(Player.class );
	}
	
	@Override
	public List<Player> getAll() {
		return super.findAll();
	}

	@Override
	public Player getPlayer(Long id) {
		return super.findOne(id);
	}

	@Override
	public List<Long> getPlayerIds(ActiveTweeter activeTweeter) {
		return entityManager.createQuery("select distinct p.id from Player p where p.activeTweeter = :activeTweeter",
				Long.class).setParameter("activeTweeter", Boolean.valueOf(activeTweeter.ordinal()!=0)).getResultList();
	}

	@Override
	public Player getPlayerWithTweets(Long playerId,ActiveTweeter activeTweeter) {
		  TypedQuery<Player> query = entityManager.createQuery("select distinct p from Player p left join fetch p.tweets t where p.id = :playerId and p.activeTweeter=:activeTweeter order by t.createdAt",
				Player.class);
		  query.setParameter("playerId", playerId);
		  query.setParameter("activeTweeter", Boolean.valueOf(activeTweeter.ordinal()!=0));
		  List<Player> resultList = query.getResultList();
		  if(!resultList.isEmpty())
			 return resultList.get(0);
		  else
			  return new NullPlayer();
	}

	@Override
	public Player getPlayerWithTweetsFromToDate(Long playerId, Date from, Date to) {
		TypedQuery<Player> createQuery = entityManager.createQuery(
				"select distinct p from Player p left join fetch p.tweets t"
						+ " where p.id = :playerId"
						+ " and t.createdAt between :from and :to",
				Player.class);
		createQuery.setParameter("playerId", playerId);
		createQuery.setParameter("from", from);
		createQuery.setParameter("to", to);

		 List<Player> resultList = createQuery.getResultList();
		  if(!resultList.isEmpty())
			 return resultList.get(0);
		  else
			  return new NullPlayer();
	}
	
	@Transactional(readOnly=false)
	@Override
	public Player updatePlayer(Player player) {
		super.update(player);
		return player;
	}
	
	@Transactional(readOnly=false)
	@Override
	public Player savePlayer(Player player) {
		super.save(player);
		return player;
	}
	
	@Transactional(readOnly=false)
	@Override
	public Player deletePlayer(Player player) {
		 super.delete(player);
		 return player;
	}
	

}
